﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Core.Extensions;
using App.Data;
using System.IO;

public partial class Pages_Admin_ArticleEdit : BasePage
{
    private int _ID = 0;
    private bool _IsEditMode = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropDownLists();
            BindArticleInfo();
        }
    }
    /// <summary>
    /// Bindis the Page Initialization Variables
    /// </summary>
    protected void BindPageInfo()
    {
        _ID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        if (_ID > 0)
        {
            _IsEditMode = true;
            h4Heading.InnerHtml = "Edit Article";
        }
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
        lblFormTitle.Text = h4Heading.InnerHtml;
    }

    /// <summary>
    /// Binds Dropdownlists for the initial request.
    /// </summary>
    protected void BindDropDownLists()
    {
        //BindDropdownList.Users(ddlModifiedBy);
    }
    /// <summary>
    /// Binds News Info Requested through Query Strings
    /// </summary>
    protected void BindArticleInfo()
    {
        if (_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            Article entity = context.Articles.FirstOrDefault(P => P.ID == _ID);//dao.GetByID(_ID);
            if (entity == null)
                ShowErrorMessage();
            else
            {
                txtTitle.Text = entity.Title;
                txtArticleContent.Text = entity.ArticleContent;
                txtPublishedOn.Text = entity.PublishedOn.ToString(ConfigReader.CSharpCalendarDateFormat);
                if (!entity.Image1.IsNullOrEmpty())
                {
                    hplImage1.NavigateUrl = String.Format("{0}/{1}", AppConstants.ARTICLE_FILES, entity.Image1);
                    hplImage1.Text = String.Format("{0}<br />", WebUtil.GetFormattedFileName(entity.Image1));
                    hplImage1.Visible = true;
                }
                //txtImage1.Text = entity.Image1;
                //txtImage2.Text = entity.Image2;
                //txtImage3.Text = entity.Image3;
                //chkIsDeleted.Checked = entity.IsDeleted;
            }
        }
    }
    /// <summary>
    /// Shows a Message in the UI and Hides the Data Editing Controls
    /// </summary>
    protected void ShowErrorMessage()
    {
        pnlFormContainer.Visible = false;
        WebUtil.ShowMessageBox(divMessage, "Requested News was not found.", true);
    }
    protected void SaveNews()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        Article entity = null;

        if (_IsEditMode)
            entity = context.Articles.FirstOrDefault(P => P.ID == _ID); //dao.GetByID(_ID);        
        else
        {
            entity = new Article();
            entity.Created = DateTime.Now;
            context.AddToArticles(entity);
        }

        entity.Title = txtTitle.Text;
        entity.ArticleContent = txtArticleContent.Text;
        entity.PublishedOn = txtPublishedOn.Text.ToDateTime(ConfigReader.CSharpCalendarDateFormat); ;
        //entity.Image1 = txtImage1.Text;
        //entity.Image2 = txtImage2.Text;
        //entity.Image3 = txtImage3.Text;
        entity.Modified = DateTime.Now;
        entity.ModifiedBy = SessionCache.CurrentUser.ID;
        entity.IsDeleted = false;
        
        context.SaveChanges();
        if (fuImage1.HasFile)
        {
            String filePath = Server.MapPath(AppConstants.ARTICLE_FILES);
            if(!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            ///Delete Existing Image at first
            if (_IsEditMode && !entity.Image1.IsNullOrEmpty())
            {
                String file = Path.Combine(filePath, entity.Image1);
                if (File.Exists(file))
                    File.Delete(file);
            }
            ///Save the File in Local Directory
            String fileName = String.Format("{0}_{1}", entity.ID, Path.GetFileName(fuImage1.FileName));
            fuImage1.SaveAs(Path.Combine(filePath, fileName));

            entity.Image1 = fileName;
            context.SaveChanges();
        }
        WebUtil.ShowMessageBox(divMessage, "News Saved Successfully.", false);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (fuImage1.HasFile && !WebUtil.IsValidImageFile(fuImage1.PostedFile))
            {
                WebUtil.ShowMessageBox(divMessage, "Please select a valid image file for news Photo", true);
                return;
            }            
            SaveNews();   
            Response.Redirect(AppConstants.Pages.ARTICLE_LIST_ADMIN);
            return;
        }
    }
    protected void btnList_Click(object sender, EventArgs e)
    {
        //Response.Redirect(AppConstants.Pages.NEWS_LIST);
        //return;
    }
}